from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import redis
from config import DATABASE_CONFIG, DATABASE_TYPE
from log import logger

from sqlalchemy.dialects.postgresql.base import PGDialect

PGDialect._get_server_version_info = lambda *args: (9, 2)

logger.debug("数据库连接方式: {}".format(DATABASE_TYPE))
SQLALCHEMY_DATABASE_URL = "{}://{}:{}@{}/{}".format(
    DATABASE_TYPE,
    DATABASE_CONFIG.get("username", "root"),
    DATABASE_CONFIG.get("password", "root"),
    DATABASE_CONFIG.get("address", "127.0.0.1:5432"),
    DATABASE_CONFIG.get("database", "soms"),
)

# 创建数据库引擎
engine = create_engine(SQLALCHEMY_DATABASE_URL)
# 创建数据库会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 声明基类
Base = declarative_base()

# 测试数据库连接
try:
    engine.connect()
    logger.debug("数据库连接成功!")
except Exception as e:
    logger.error(f'数据库连接失败! 请检查配置文件是否正确! error message: {e}')
    import sys
    sys.exit(0)

# 连接redis
redis_db = redis.Redis(host='localhost', port=6379, db=0)

# 测试redis
try:
    redis_db.ping()
    logger.debug("Redis连接成功!")
except redis.ConnectionError as e:
    logger.error(f'Redis连接失败! 请检查配置文件是否正确! error message: {e}')
    import sys
    sys.exit(0)

